<template>
    <div>
        <div class="header">
            <div class="page-header">
                <el-page-header @back="goBack" content="代码生成器"></el-page-header>
            </div>

            <el-select v-model="importTableName" filterable placeholder="请选择"
                       size="small" @visible-change="handleVisibleChange"
                       style="margin-top:10px;margin-left: 40px">
                <el-option
                        v-for="item in importOptions"
                        :key="item.value"
                        :label="item.value"
                        :value="item.value">
                </el-option>
            </el-select>

            <el-button type="success" icon="el-icon-plus" @click="improtTbale" size="small"
                       :disabled="canImport" style="margin-top:10px;margin-left: 20px">导入表
            </el-button>


            <el-button type="danger" icon="el-icon-delete" @click="deleteTable()" size="small"
                       :disabled="caneleteable" style="margin-top:10px;margin-left: 40px">批量删除
            </el-button>

            <div class="search">
                <el-input v-model="pageRequest.key" style="width: 200px;margin-right: 10px"
                          placeholder="按数据表名称查找"
                          size="small"></el-input>
                <el-button type="primary" icon="el-icon-search" size="small" @click="getTableList">搜索</el-button>
            </div>

        </div>
        <el-card class="box-card" shadow="always">
            <template>
                <el-table
                        ref="multipleTable"
                        @selection-change="handleSelectionChange"
                        :header-cell-style="{color:'#333',fontFamily:'MicrosoftYaHeiUI',fontSize:'14px',fontWeight:900}"
                        size="mini" :data="tableList" style="width: 100%">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="tableComment" label="模块名称" :show-overflow-tooltip='true'></el-table-column>
                    <el-table-column prop="tableSchema" label="数据库名" :show-overflow-tooltip='true'></el-table-column>
                    <el-table-column prop="tableName" label="表名" :show-overflow-tooltip='true'></el-table-column>
                    <el-table-column prop="entityName" label="实体对象" :show-overflow-tooltip='true'></el-table-column>
                    <el-table-column prop="primaryKey" label="主键" :show-overflow-tooltip='true'></el-table-column>
                    <el-table-column
                            label="操作"
                            width="200">
                        <template slot-scope="scope">
                            <el-button @click="editForm(scope.row)"
                                       icon="el-icon-edit" type="text"
                                       :disabled="scope.row.flag===true"
                                       size="mini">编辑
                            </el-button>
                            <el-button @click="generateCode(scope.row)"
                                       v-if="scope.row.flag === false"
                                       icon="el-icon-document" type="text"
                                       size="mini">生成代码
                            </el-button>
                            <el-button @click="uninstall(scope.row)"
                                       v-if="scope.row.flag === true"
                                       icon="el-icon-document" type="text"
                                       size="mini">卸载代码
                            </el-button>

                            <el-button @click="deleteTable(scope.row)"
                                       :disabled="scope.row.flag===true"
                                       icon="el-icon-delete" type="text"
                                       size="small">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <div class="block">
                <el-pagination
                        style="float: right"
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageRequest.pageNum"
                        :page-sizes="[10, 50, 100, 200]"
                        :page-size="pageRequest.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageResult.total">
                </el-pagination>
            </div>
        </el-card>
        <div>
            <el-dialog
                    width="700px"
                    top="5vh"
                    :title="operate.title"
                    :visible.sync="dialogFormVisible">
                <el-form :inline="true" :model="form" :rules="TableRules" ref="form" style="padding: 0px 50px"
                         size="small">
                    <el-form-item label="模块名称" :label-width="formLabelWidth" prop="tableComment">
                        <el-input v-model="form.tableComment" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="实体类" :label-width="formLabelWidth" prop="entityName">
                        <el-input v-model="form.entityName" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel" size="medium">取 消</el-button>
                    <el-button type="primary"
                               @click="submitUpdate('form')"
                               size="medium">确 定
                    </el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import {
        addTable,
        deleteTable, generateCode,
        getTableList, getTableNames, importTable, uninstall,
        updateTable
    } from "../../api/table";
    import {mapActions} from "vuex";
    import MessageUtil from "@/utils/MessageUtil";
    import MessageBoxUtil from "@/utils/MessageBoxUtil";
    import {restart} from "@/api/application";
    import DeepCopyUtil from "@/utils/DeepCopyUtil";

    export default {
        name: 'TableManage.vue',
        data() {
            return {
                options: [{
                    value: '选项1',
                    label: '黄金糕'
                }, {
                    value: '选项2',
                    label: '双皮奶'
                }, {
                    value: '选项3',
                    label: '蚵仔煎'
                }, {
                    value: '选项4',
                    label: '龙须面'
                }, {
                    value: '选项5',
                    label: '北京烤鸭'
                }],
                value: '',
                tableList: [],
                pageRequest: {
                    pageNum: 1,
                    pageSize: 10,
                    key: ''
                },
                pageResult: {
                    total: 0,
                    totalPage: 0,
                    size: 0,
                },
                dialogFormVisible: false,
                formLabelWidth: '90px',
                multipleSelection: [],
                operate: {
                    opType: 0,
                    title: ''
                },
                form: {},
                importOptions: [],
                importTableName: '',
                TableRules: {
                    tableId: [
                        {required: true, message: 'tableId不能为空', trigger: 'blur'}
                    ],
                    tableSchema: [
                        {required: true, message: 'tableSchema不能为空', trigger: 'blur'}
                    ],
                    tableName: [
                        {required: true, message: 'tableName不能为空', trigger: 'blur'}
                    ],
                    tableComment: [
                        {required: true, message: 'tableComment不能为空', trigger: 'blur'}
                    ],
                    entityName: [
                        {required: true, message: 'entityName不能为空', trigger: 'blur'}
                    ]
                },
            }
        },
        //监听属性 类似于data概念
        computed: {
            canImport() {
                return this.importTableName === '';
            },
            caneleteable() {
                return this.multipleSelection.length === 0
            }
        },
        //监控data中的数据变化
        watch: {},
        //方法集合
        methods: {
            ...mapActions('menu', ['refreshMenu']),

            editForm(row) {
                this.dialogFormVisible = true;
                this.form = DeepCopyUtil.copy(row);
                this.operate.title = "编辑数据表"
            },
            getTableList() {
                getTableList(this.pageRequest).then(res => {
                    if (res.code === 200) {
                        this.tableList = res.data.dataList
                        this.pageResult.size = res.data.size
                        this.pageResult.total = res.data.total
                        this.pageResult.totalPage = res.data.totalPage
                        if (res.data.size === 0 && res.data.pageNum > 1) {
                            this.pageRequest.pageNum--;
                            this.tableList();
                        }
                    }
                }).catch(err => {
                    console.log(err)
                })
            },
            deleteTable(row) {
                MessageBoxUtil.confirm("此操作将永久删除该数据, 是否继续?", 'warn', () => {
                    if (row) {
                        this.multipleSelection = [row]
                    }
                    deleteTable(this.multipleSelection).then(res => {
                        if (res.code === 200) {
                            this.getTableList();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败，' + res.message,
                            });
                        }
                    }).catch(err => {
                        this.$message({
                            type: 'error',
                            message: '删除失败，' + err.message
                        });
                    })
                })
            },
            submitUpdate(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        updateTable(this.form).then(res => {
                            if (res.code === 200) {
                                this.dialogFormVisible = false;
                                this.getTableList()
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: '修改失败，' + res.message,
                                    type: 'error'
                                });
                            }
                        }).catch(err => {
                            this.$message({
                                message: '修改失败，' + err.message,
                                type: 'error'
                            });
                        })
                    } else {
                        return false;
                    }
                });
            },
            getTableNames() {
                getTableNames().then(res => {
                    if (res.code === 200) {
                        let tableNames = res.data;
                        let options = [];
                        for (let tableName of tableNames) {
                            options.push({value: tableName})
                        }
                        console.log(options)
                        this.importOptions = options;
                    }
                }).catch(err => {
                })
            },
            improtTbale() {
                importTable({tableName: this.importTableName}).then(res => {
                    if (res.code === 200) {
                        this.getTableList()
                        MessageUtil.success("导入成功")
                    } else {
                        MessageUtil.error('导入失败，' + res.message)
                    }
                }).catch(err => {
                    MessageUtil.error("导入失败，" + err.message)
                })
            },
            generateCode(row) {
                MessageBoxUtil.confirm('点击确认将开始进行代码生成, 是否继续?', 'info', () => {
                    generateCode(row).then(res => {
                        if (res.code === 200) {
                            this.getTableList()
                            // this.restartApplication()
                            MessageUtil.success("代码生成成功")
                        } else {
                            MessageUtil.error("代码生成失败，" + res.message)
                        }
                    }).catch(err => {
                        MessageUtil.error("代码生成失败，" + err.message)
                    })
                })
            },
            uninstall(row) {
                MessageBoxUtil.confirm('点击确认将删除已生成代码, 是否继续?', 'info', () => {
                    uninstall(row).then(res => {
                        if (res.code === 200) {
                            this.getTableList()
                            MessageUtil.success("卸载成功")
                        } else {
                            MessageUtil.error("卸载失败，" + res.message)
                        }
                    }).catch(err => {
                        MessageUtil.error("卸载失败，" + err.message)
                    })
                })
            },
            restartApplication() {
                restart().then(res => {

                }).catch(err => {

                })
            },
            cancel() {
                this.dialogFormVisible = false;
                this.getTableList()
            },
            handleSizeChange(pageSize) {
                this.pageRequest.pageSize = pageSize;
                this.getTableList()
            },
            handleCurrentChange(pageNum) {
                this.pageRequest.pageNum = pageNum;
                this.getTableList()
            },
            handleSelectionChange(rows) {
                this.multipleSelection = rows;
            },
            handleVisibleChange(visible) {
                if (visible) {
                    this.getTableNames()
                }
            },
            goBack() {
                window.history.back()
            },
        },
        //生命周期 - 创建完成（可以访问当前this实例）
        created() {
            this.getTableList();
        },
        //生命周期 - 挂载完成（可以访问DOM元素）
        mounted() {
        },
    };
</script>

<style scoped>

    .header {
        /*display: flex;*/
        /*!*垂直对齐*!*/
        /*align-items: center;*/
        height: 50px;
        background-color: #eff4f9;
    }

    .page-header {
        float: left;
        margin-top: 15px
    }

    .search {
        float: right;
        margin-top: 10px
    }

    .box-card {
        height: 100%;
        padding-bottom: 5px;
    }

    .block {
        margin-top: 5px;
    }

    .el-input, .el-select {
        width: 170px
    }

    .el-form-item {
        width: 260px;
    }

    .el-form {
        padding: 0 20px;
    }

</style>
